
package com.hyst.seviceImpl;

import java.util.*;

import com.hyst.common.ResultBean;
import com.hyst.domain.*;
import com.hyst.repository.*;
import com.hyst.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hyst.domain.Period;
import com.hyst.domain.PeriodEdits;
import com.hyst.domain.Student;
import com.hyst.domain.TeacherPeriod;
import com.hyst.domain.TeacherPeriodUsed;
import com.hyst.domain.TeacherSchedule;
import com.hyst.service.TeacherPeriodService;
import com.hyst.utils.UuidTool;

/**
 * @version ：1.0 1.[2018年08月25日]
 */
@Service
public class TeacherPeriodServiceImpl implements TeacherPeriodService {

    @Autowired
    private TeacherPeriodMapper mapper;

    @Autowired
    private PeriodMapper periodMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherPeriodUsedMapper mapperused;

    @Autowired
    private FreeAuditionMapper freeAuditionMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    private static final List<String> PE = Arrays.asList("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

    @Override
    public Page<TeacherPeriod> list(final TeacherPeriod teacherPeriod) {
        final Page<TeacherPeriod> page = PageHelper.startPage(teacherPeriod.getPageNum(), teacherPeriod.getPageSize());
//		mapper.select(teacherPeriod);
        mapper.select(teacherPeriod);
        return page;
    }


    @Override
    public ResultBean<List<List<TeacherPeriod>>> teacherPeriods(TeacherPeriod teacherPeriod){
        List<TeacherPeriod> select = mapper.select(teacherPeriod);
        Map<String,List<TeacherPeriod>> week=new HashMap<>();
        for(TeacherPeriod period:select){
            String checkid = period.getCheckid();
            if(week.containsKey(checkid)){
                List<TeacherPeriod> teacherPeriods = week.get(checkid);
                teacherPeriods.add(period);
            }else {
                List<TeacherPeriod> teacherPeriods = new ArrayList<>();
                teacherPeriods.add(period);
                week.put(checkid,teacherPeriods);
            }
        }

        List<List<TeacherPeriod>> periodArray = new ArrayList<>();
        for (List<TeacherPeriod> pd:week.values()){
            if(pd.size()>1){
                List<TeacherPeriod> periodsNew = new ArrayList<>();
                for(TeacherPeriod pp :pd){
                    if(!pp.getStatus().equals("可用")){
                        periodsNew.add(pp);
                    }
                }
                periodArray.add(periodsNew);
            }else {
                periodArray.add(pd);
            }
        }
        return ResultBean.success(periodArray);
    }


    @Override
    public Page<TeacherPeriodUsed> getPeriodUsedlist(TeacherPeriodUsed teacherPeriodUsed) {
        final Page<TeacherPeriodUsed> page = PageHelper.startPage(teacherPeriodUsed.getPageNum(),
                teacherPeriodUsed.getPageSize());
        mapperused.getPeriodUsed(teacherPeriodUsed);
        return page;
    }

    @Override
    public Page<TeacherPeriodUsed> getPeriodUsedFormal(TeacherPeriodUsed teacherPeriodUsed) {
        final Page<TeacherPeriodUsed> page = PageHelper.startPage(teacherPeriodUsed.getPageNum(),
                teacherPeriodUsed.getPageSize());
        mapperused.getPeriodUsedFormal(teacherPeriodUsed);
        return page;
    }

    @Override
    public TeacherPeriod insert(final TeacherPeriod teacherPeriod) {
        mapper.insertSelective(teacherPeriod);
        return teacherPeriod;
    }

    @Override
    public TeacherPeriod getByPriKey(final Integer id) {
        final TeacherPeriod teacherPeriod = mapper.selectByPrimaryKey(id);
        return teacherPeriod;
    }

    @Override
    public TeacherPeriod updateSelective(final TeacherPeriod teacherPeriod) {
        mapper.updateByPrimaryKeySelective(teacherPeriod);
        return teacherPeriod;
    }

    @Override
    public TeacherPeriod update(final TeacherPeriod teacherPeriod) {
        mapper.updateByPrimaryKey(teacherPeriod);
        return teacherPeriod;
    }

    @Override
    public TeacherPeriod delete(final Integer id) {

        return null;
    }

    @Override
    public int save(String teacherId, List<TeacherPeriod> list) {
        TeacherPeriod teacherPeriod = new TeacherPeriod();
        teacherPeriod.setTeacherid(teacherId);
        int s = mapper.delete(teacherPeriod);
        System.out.println("删除了{0}条记录\t" + s);
        int j = 0;
        for (TeacherPeriod t : list) {
            System.err.println(t);
            j += mapper.insertSelective(t);
        }
        return j;
    }

    @Override
    public String savePeriodUsed(String teacherId, List<TeacherPeriodUsedCusmom> list) {
        String date = teacherId.split("&")[1];
        teacherId = teacherId.split("&")[0];
//        String orderId= teacherId.split("&")[2];
        int j = 0;
        String studentId = "";
        StringBuilder timeBuilder = new StringBuilder();
        try {
            for (TeacherPeriodUsedCusmom t : list) {
                studentId = t.getStudentid();
                if ("delete".equals(t.getSdStatus())) {
                    TeacherPeriod teacherPeriodUsed = new TeacherPeriod();
                    teacherPeriodUsed.setTeacherid(teacherId);
                    teacherPeriodUsed.setCheckid(t.getCheckid());
                    teacherPeriodUsed.setStudentid(t.getStudentid());
//                    teacherPeriodUsed.setUseMsg(t.getUseMsg());
                    teacherPeriodUsed.setStatus("试听");
                    mapper.deletePeriod(teacherPeriodUsed);
                } else if ("add".equals(t.getSdStatus())) {

                    TeacherPeriod period = (TeacherPeriod) t;
                    List<TeacherPeriod> useds = mapperused.selectPeriod(period);

                    String stuName = mapper.getStuName(period.getStudentid());
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(stuName)){
                        period.setUseMsg(stuName + "试听");
//                        period.setPurchaseCourseUid(orderId);
                        if (useds.size() <= 0) {
                            mapper.insertSelective(period);
                        } else {
                            for (TeacherPeriod tp : useds) {
                                if (!tp.getDate().equals(date)) {
                                    period.setId(tp.getId());
                                    mapperused.updateTime(period);
                                }
                            }
                        }
                    }
                }
            }
            int index = 0;
            if (org.apache.commons.lang3.StringUtils.isNotBlank(studentId)) {
                //更新教师
                FreeAudition freeAudition = new FreeAudition();
                freeAudition.setTeacherId(teacherId);
                Teacher teacher = new Teacher();
                teacher.setUniqueid(teacherId);
                teacher = teacherMapper.selectById(teacherId);
                freeAudition.setTeacherName(teacher.getName());
                freeAudition.setOrderId(studentId);
//                freeAuditionMapper.updateTeacher(freeAudition);

                timeBuilder.append(date).append(" ");
                Map<String, Object> sqlMap = new HashMap<>();
                sqlMap.put("studentid", studentId);
                sqlMap.put("teacherid", teacherId);
                List<TeacherPeriod> teacherPeriodUsed = freeAuditionMapper.selectListern(sqlMap);
                String weekF = "";
                for (TeacherPeriod used : teacherPeriodUsed) {
                    index++;
                    String week = used.getWeek();
                    Integer timeId = used.getTimeid();

                    Period period = freeAuditionMapper.selectPeriod(timeId);
                    String name = period.getName();
                    String pe = PE.get(Integer.valueOf(week) - 1);

                    if (weekF.equals(week)) {
                        timeBuilder.append(" ").append(name);
                    } else if (index == 0) {
                        timeBuilder.append(pe + " ").append(name);
                        weekF = week;
                        index++;
                    } else {
                        timeBuilder.append(", ").append(pe + " ").append(name);
                        weekF = week;
                    }
                }
                System.out.println(timeBuilder.toString());
                freeAudition.setAuditionTime(timeBuilder.toString());
                freeAuditionMapper.updateFreeAuditionTime(freeAudition);
            }
            if (index <= 0) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeBuilder.toString();
    }

    @Override
    public String savePeriodFormUsed(String teacherId, List<TeacherPeriodUsedCusmom> list) {
        String date = teacherId.split("&")[1];
        teacherId = teacherId.split("&")[0];
        String auditionTime = "";
        String studentid = "";
        StringBuilder timeBuilder = new StringBuilder();
        int j = 0;
        try {
            for (TeacherPeriodUsedCusmom t : list) {
                studentid = t.getStudentid();
                if ("保留".equals(t.getStatus())) {
                    if ("delete".equals(t.getSdStatus())) {
                        TeacherPeriod teacherPeriodUsed = new TeacherPeriod();
                        teacherPeriodUsed.setTeacherid(teacherId);
                        teacherPeriodUsed.setCheckid(t.getCheckid());
                        teacherPeriodUsed.setStudentid(t.getStudentid());
//                        teacherPeriodUsed.setUseMsg(t.getUseMsg());
                        teacherPeriodUsed.setStatus("保留");
                        mapper.deletePeriod(teacherPeriodUsed);
                    } else if ("add".equals(t.getSdStatus())) {
                        TeacherPeriod period = (TeacherPeriod) t;
                        List<TeacherPeriod> useds = mapperused.selectPeriod(period);

                        String stuName = mapper.getStuName(period.getStudentid());
                        if(org.apache.commons.lang3.StringUtils.isNotBlank(stuName)){
                            period.setUseMsg(stuName + "保留");
                            if (useds.size() <= 0) {
                                mapper.insertSelective(period);
                            } else {
//                            for (TeacherPeriod tp : useds) {
//                                if (tp.getDate()!tp.getDate().equals(date)) {
//                                    period.setId(tp.getId());
//                                    mapperused.updateTime(period);
//                                }
//                            }
                            }
                        }

                    }
                }
            }

            if (org.apache.commons.lang3.StringUtils.isNotBlank(studentid)) {
                //更新教师
                FreeAudition freeAudition = new FreeAudition();
                freeAudition.setTeacherId(teacherId);
                Teacher teacher = new Teacher();
                teacher.setUniqueid(teacherId);
                teacher = teacherMapper.selectById(teacherId);
                freeAudition.setTeacherName(teacher.getName());
                freeAudition.setOrderId(studentid);
//                freeAuditionMapper.updateTeacher(freeAudition);

                Map<String, Object> sqlMap = new HashMap<>();
                sqlMap.put("studentid", studentid);
                sqlMap.put("teacherid", teacherId);
                List<TeacherPeriod> teacherPeriodUsed = freeAuditionMapper.selectFormal(sqlMap);
                String weekF = "";
                int index = 0;
                for (TeacherPeriod used : teacherPeriodUsed) {
                    String week = used.getWeek();
                    Integer timeId = used.getTimeid();

                    Period period = freeAuditionMapper.selectPeriod(timeId);
                    String name = period.getName();
                    String pe = PE.get(Integer.valueOf(week) - 1);

                    if (weekF.equals(week)) {
                        timeBuilder.append(" ").append(name);
                    } else if (index == 0) {
                        timeBuilder.append(pe + " ").append(name);
                        weekF = week;
                        index++;
                    } else {
                        timeBuilder.append(", ").append(pe + " ").append(name);
                        weekF = week;
                    }
                }
                System.out.println(timeBuilder.toString());
                freeAudition.setFormalTime(timeBuilder.toString());
                freeAuditionMapper.updateFreeFormalTime(freeAudition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeBuilder.toString();
    }

    @Override
    public Page<TeacherSchedule> getTeacherSchedules(TeacherSchedule ts) {
        Page<TeacherSchedule> page = PageHelper.startPage(1, 40);
        mapper.getTeacherSchedules(ts);
        return page;
    }

    @Override
    public int savePeriods(PeriodEdits periodEdits) {
        List<String> ids = periodEdits.getDels();
        int num = 0;
        if (ids != null && ids.size() > 0) {
            num += mapper.deleteAll(ids);
            System.err.println(num);
        }
        List<TeacherPeriod> periods = periodEdits.getAdds();
        if (periods != null && periods.size() > 0) {

            num += mapper.insetAll(periods);
        }
        if (periodEdits.getRetentions() != null && periodEdits.getRetentions().size() > 0) {
            num += mapper.retentions(periodEdits);
        }
        return num;
    }

    @Override
    public String getAuditionTime(String studentId,String teacherid) {
        try {
            Map<String, Object> sqlMap = new HashMap<>();
            sqlMap.put("teacherId", teacherid);
            sqlMap.put("orderId", studentId);
            String teacherPeriod = mapper.getAuditionTime(sqlMap);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(teacherPeriod)) {
                return teacherPeriod.split(" ")[0];
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
